<?php


namespace app\common\server;

class StatisticsData
{
	public static function increases($appid, $type, $data, $others_1 = false, $others_2 = false, $others_3 = false)
	{
		self::add($appid, $type, "Y", date("Y"), $data, $others_1, $others_2, $others_3);
		self::add($appid, $type, "Ym", date("Ym"), $data, $others_1, $others_2, $others_3);
		self::add($appid, $type, "Ymd", date("Ymd"), $data, $others_1, $others_2, $others_3);
		self::add($appid, $type, "YmdH", date("YmdH"), $data, $others_1, $others_2, $others_3);
		self::add($appid, $type, "YW", date("YW"), $data, $others_1, $others_2, $others_3);
	}
	public static function add($appid, $type, $time_format, $time_value, $data, $others_1 = false, $others_2 = false, $others_3 = false)
	{
		$where[] = ["appid", "=", $appid];
		$where[] = ["type", "=", $type];
		$where[] = ["time_format", "=", $time_format];
		$where[] = ["time_value", "=", $time_value];
		if ($others_1 !== false) {
			$where[] = ["others_1", "=", $others_1];
		}
		if ($others_2 !== false) {
			$where[] = ["others_2", "=", $others_2];
		}
		if ($others_3 !== false) {
			$where[] = ["others_3", "=", $others_3];
		}
		$record = \think\Db::name("app_data")->where($where);
		if (isset($record) && $record->value("id")) {
			return $record->setInc("data", $data);
		} else {
			$data = ["appid" => $appid, "type" => $type, "time_format" => $time_format, "time_value" => $time_value, "data" => $data, "others_1" => $others_1 ?? "", "others_2" => $others_2 ?? "", "others_3" => $others_3 ?? ""];
			return \think\Db::name("app_data")->insert($data);
		}
	}
	public static function get($appid, $type, $time_format, $time_value, $default = false, $others_1 = false, $others_2 = false, $others_3 = false)
	{
		$where[] = ["appid", "=", $appid];
		$where[] = ["type", "=", $type];
		$where[] = ["time_format", "=", $time_format];
		$where[] = ["time_value", "=", $time_value];
		if ($others_1 !== false) {
			$where[] = ["others_1", "=", $others_1];
		}
		if ($others_2 !== false) {
			$where[] = ["others_2", "=", $others_2];
		}
		if ($others_3 !== false) {
			$where[] = ["others_3", "=", $others_3];
		}
		$record = \think\Db::name("app_data")->where($where)->value("data");
		if (isset($record) && $record) {
			return $record;
		} else {
			return $default;
		}
	}
	public static function sum($appid, $type, $time_format, $time_value, $others_1 = false, $others_2 = false, $others_3 = false)
	{
		$where[] = ["appid", "=", $appid];
		$where[] = ["type", "=", $type];
		$where[] = ["time_format", "=", $time_format];
		$where[] = ["time_value", "=", $time_value];
		if ($others_1 !== false) {
			$where[] = ["others_1", "=", $others_1];
		}
		if ($others_2 !== false) {
			$where[] = ["others_2", "=", $others_2];
		}
		if ($others_3 !== false) {
			$where[] = ["others_3", "=", $others_3];
		}
		$number = \think\Db::name("app_data")->where($where)->sum("data");
		return $number;
	}
}